package com.hongxun.budget.ui.activity.tk;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hongxun.budget.R;
import com.hongxun.budget.greendao.APBaseEntityDao;
import com.hongxun.budget.ui.activity.BaseListActivity;
import com.hongxun.budget.ui.dialog.ListDialog;
import com.hongxun.budget.utils.DBUtils;
import com.hongxun.budget.utils.DateUtils;
import com.hongxun.budget.utils.GreenDaoManager;
import com.hongxun.budget.utils.SPUtils;
import com.hongxun.budget.utils.T;
import com.hongxun.budget.utils.XUtils;
import com.hongxun.greenentity.tk.APBaseEntity;
import com.hongxun.interfaces.ResponseListener;
import com.hongxun.net.ProjectNet;
import com.jessewu.library.SuperAdapter;
import com.jessewu.library.view.ViewHolder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class ProjectListActivity extends BaseListActivity {


    @BindView(R.id.right_save)
    Button rightSave;
    @BindView(R.id.right_btn)
    Button rightBtn;
    List<APBaseEntity> datas = new ArrayList<>();
    List<APBaseEntity> localDatas = new ArrayList<>();
    SuperAdapter<APBaseEntity> superAdapter;
    int flag = 0;//0-本地，1-服务器

    String uuid;


    @Override
    public SuperAdapter getAdapter() {
        return superAdapter = new SuperAdapter<APBaseEntity>(R.layout.content_project) {
            @Override
            public void bindView(final ViewHolder viewHolder, final APBaseEntity a, int i) {
                Button refreshBtn = viewHolder.getView(R.id.refresh_btn);
                ((TextView) viewHolder.getView(R.id.name)).setText(a.getPBName());
                ((TextView) viewHolder.getView(R.id.type)).setText(DBUtils.getBDataDictionaryEntity("progect_type", a.getPBType()).getDValue());
                ((TextView) viewHolder.getView(R.id.time)).setText(DateUtils.DateToString(a.getPBAddtime()));
                if (flag == 0) {
                    refreshBtn.setText("明细");
                    refreshBtn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            SPUtils.put(context, "project_guid", a.getGuid());
                            startActivity(new Intent(context, ProjectDetailActivity.class));
                        }
                    });
                    viewHolder.getView(R.id.layout).setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View view) {
                            ListDialog<String> dialog = new ListDialog<String>();
                            dialog.setTitle("请选择").setDatas(Arrays.asList(getResources().getStringArray(R.array.operation))).setListener(new ResponseListener() {
                                @Override
                                public void response(Object... data) {
                                    String result = (String) data[0];
                                    if (result.equals("编辑项目")) {
                                        SPUtils.put(context, "project_guid", a.getGuid());
                                        Intent intent = new Intent(context, ProjectCreateActivity.class);
                                        intent.putExtra("update", true);
                                        startActivity(intent);
                                    } else {//删除
                                        if (a.getGuid().equals((String) SPUtils.get(context, "project_guid", ""))) {
                                            SPUtils.remove(context, "project_guid");
                                        }
                                        XUtils.deleteProject(a.getGuid());
                                        localDatas.remove(a);
                                        T.showLong(context, "删除成功");
                                        datas.remove(a);
                                        superAdapter.notifyDataSetChanged();
                                    }
                                }
                            }).show(getFragmentManager(), "");
                            return false;
                        }
                    });
                    viewHolder.getView(R.id.layout).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            SPUtils.put(context, "project_guid", a.getGuid());
                            startActivity(new Intent(context, ProjectActivity.class));
                        }
                    });
                } else {
                    refreshBtn.setText("更新");
                    viewHolder.getView(R.id.layout).setClickable(false);
                    viewHolder.getView(R.id.layout).setLongClickable(false);
                    refreshBtn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            uuid = a.getGuid();
                            if (isVisibleProject(a)) {//存在则先上传，后下载
                                ProjectNet.updateProject(context, uuid, ProjectListActivity.this);
                            } else {//直接下载
                                ProjectNet.downProject(context, uuid, ProjectListActivity.this);//下载项目
                            }
                        }
                    });
                }
            }
        };
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        rightBtn.setText("本地");
        rightSave.setText("服务器");
        rightBtn.setVisibility(View.VISIBLE);
        rightSave.setVisibility(View.VISIBLE);
        setBtnColor();
        superAdapter.setData(datas);
        superAdapter.setEmptyDataView(R.layout.view_empty);
        getData();


    }

    void setBtnColor() {
        if (flag == 0) {
            rightBtn.setTextColor(getResources().getColor(R.color.colorAccent));
            rightSave.setTextColor(getResources().getColor(R.color.black));
        } else {
            rightBtn.setTextColor(getResources().getColor(R.color.black));
            rightSave.setTextColor(getResources().getColor(R.color.colorAccent));
        }
    }

    public void getData() {
        datas.clear();
        localDatas.clear();
        localDatas.addAll(GreenDaoManager.getInstance().getmDaoSession().getAPBaseEntityDao().queryBuilder()
                .where(APBaseEntityDao.Properties.PBDatastate.notEq("删除")).orderDesc(APBaseEntityDao.Properties.PBAddtime).list());
        datas.addAll(localDatas);//默认本地数据
        superAdapter.notifyDataSetChanged();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @OnClick({R.id.right_btn, R.id.right_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.right_btn:
                flag = 0;
                datas.clear();
                datas.addAll(localDatas);
                superAdapter.notifyDataSetChanged();
                break;
            case R.id.right_save:
                flag = 1;
                getProjectInfo();
                break;
        }
        setBtnColor();
    }

    void getProjectInfo() {
        ProjectNet.projectInfo(context, this);
    }

    @Override
    public void success(int i, JSONObject obj) {
        switch (i) {
            case 999://获取到服务器项目列表
                List<APBaseEntity> apBaseEntities = JSON.parseArray(obj.getString("apBaseEntities"), APBaseEntity.class);
                datas.clear();//清楚数据方便刷新
                datas.addAll(localDatas);//先添加本地数据
                for (APBaseEntity a : apBaseEntities) {
                    if (!isVisibleProject(a)) {//如果本地没有包含服务器的数据则添加新的项目信息
                        datas.add(a);
                    }
                }
                superAdapter.notifyDataSetChanged();
                break;
            case 888://项目下载成功
                XUtils.downProject(context, obj, this);
                break;
            case 1:
                ProjectNet.upPhoto(context, uuid, this);//上传图片
                break;
            case 2:
                ProjectNet.projectPoint(context, uuid, this);//上传点位信息
                break;
            case 3:
                ProjectNet.projectDeviceAndMaterial(context, uuid, this);//设备及材料
                break;
            case 4:
                ProjectNet.projectCross(context, uuid, this);//工程量及工作内容
                break;
            case 5:
                ProjectNet.downProject(context, uuid, this);//下载项目
                break;
            case 6://下载并保存成功
                localDatas.clear();
                localDatas.addAll(GreenDaoManager.getInstance().getmDaoSession().getAPBaseEntityDao().queryBuilder()
                        .where(APBaseEntityDao.Properties.PBDatastate.notEq("删除")).orderDesc(APBaseEntityDao.Properties.PBAddtime).list());
                T.showLong(context, "下载成功");
                break;
        }
    }

    boolean isVisibleProject(APBaseEntity a) {
        for (APBaseEntity b : localDatas) {
            if (b.getGuid().equals(a.getGuid())) {
                return true;
            }
        }
        return false;
    }

}
